import * as motion from "motion/react-client"
import { useEffect, useRef, useState } from "react"

export default function Reordering() {
    const [order, setOrder] = useState(initialOrder)
    const timer = useRef(null)
    const [isHovered, setIsHovered] = useState(false)

    useEffect(() => {
        if (!isHovered) {
            timer.current = setTimeout(() => setOrder(shuffle(order)), 3000)
        }
        return () => clearTimeout(timer.current)
    }, [order, isHovered])

    return (
        <ul
            style={container}
            onMouseEnter={() => {
                setIsHovered(true)
            }}
            onMouseLeave={() => {
                setIsHovered(false)
            }}
        >
            {order.map((backgroundColor) => (
                <motion.li
                    key={backgroundColor}
                    layout
                    transition={spring}
                    whileHover={{ rotate: 180 }}
                    style={{ ...item, backgroundColor }}
                />
            ))}
        </ul>
    )
}

const initialOrder = [
    "#a3e",
    "#d0e",
    "#91f",
    "#8df0cc",
    "#1e75f7",
    "#0cdcf7",
    '#83e6f7',
    '#fa3',
    '#859',
    "#75f",
    "#ddc",
    '#866',
    "#77f",
    "#088",
    '#28e',
]

/**
 * ==============   Utils   ================
 */
function shuffle([...array]: string[]) {
    return array.sort(() => Math.random() - 0.5)
}

/**
 * ==============   Styles   ================
 */

const spring = {
    type: "spring",
    damping: 50,
    stiffness: 300,
}

const container: React.CSSProperties = {
    listStyle: "none",
    padding: 0,
    margin: 0,
    position: "relative",
    display: "flex",
    flexWrap: "wrap",
    gap: 10,
    width: 300,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
}

const item: React.CSSProperties = {
    width: 45,
    height: 45,
    borderRadius: "10px",
}
